# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models
from utils.models import BaseModel
from ElevatorAdmin.elevator_run_state import DEV_RUN_STATE
from basic.models import ElevatorInfo
from users.models import Person, CompanyInfo, AuthUser
import json
import datetime


# 注册
class AuthorityCode(BaseModel):
    is_online = models.BooleanField(verbose_name=u'是否在线', default=True)
    code = models.CharField(max_length=32, default=u'', verbose_name=u'鉴权码', db_index=True, null=True, blank=True)
    manufacturer_code = models.CharField(default=u'', max_length=20, verbose_name=u'厂家编号', null=True, db_index=True, blank=True)
    manufacturer_code_elevator = models.CharField(default=u'', max_length=20, verbose_name=u'电梯厂家编号', null=True, db_index=True, blank=True)
    elevator_code = models.CharField(default=u'', max_length=25, verbose_name=u'电梯注册代码', null=True, db_index=True, blank=True)
    manufacturer_number = models.CharField(default=u'', max_length=50, verbose_name=u'出厂编号', null=True, db_index=True, blank=True)
    manufacturer_number_elevator = models.CharField(default=u'', max_length=50, verbose_name=u'电梯出厂编号', null=True, db_index=True, blank=True)
    device_code = models.CharField(default=u'', max_length=50, verbose_name=u'终端编号', null=True, db_index=True, blank=True)
    device_code_elevator = models.CharField(default=u'', max_length=50, verbose_name=u'外设编号', null=True, db_index=True, blank=True)
    device_type = models.CharField(default=u'', max_length=50, verbose_name=u'终端类型', null=True, db_index=True, blank=True)
    sim_no = models.CharField(verbose_name=u'SIM卡号码', max_length=14, blank=True, null=True)    # 后续会改成13位的物流卡
    platform = models.ForeignKey('CompanyPlatform', verbose_name=u"企业平台", null=True, blank=True, db_index=True)
    bend_times = models.IntegerField(verbose_name=u'钢丝绳折弯次数', default=0)
    yesterday_bend_times = models.IntegerField(verbose_name=u'钢丝绳折弯次数', default=0)
    run_times = models.IntegerField(verbose_name=u'运行次数', default=0)
    yesterday_run_times = models.IntegerField(verbose_name=u'运行次数', default=0)
    open_times = models.IntegerField(verbose_name=u'开关门次数', default=0)
    yesterday_open_times = models.IntegerField(verbose_name=u'开关门次数', default=0)
    up_time = models.IntegerField(verbose_name=u'运行时间', default=0)
    yesterday_up_time = models.IntegerField(verbose_name=u'运行时间', default=0)
    login_time = models.IntegerField(verbose_name=u'登陆时间戳', default=0)
    start_work_time = models.IntegerField(verbose_name=u"电梯开始运行时间",default=0)  # 每次电梯开始运行改为0, 电梯停止时求总时
    start_floor = models.IntegerField(verbose_name=u"开始楼层", default=1)
    collection_num = models.CharField(default=u"", max_length=20, null=True, db_index=True, verbose_name=u"采集器编号", blank=True)
    address = models.CharField(default=u"", max_length=220, null=True, blank=True)
    maintain_company = models.ForeignKey(CompanyInfo, verbose_name=u"维保单位", null=True, blank=True,
                                         on_delete=models.SET_NULL, related_name="maintain_company_authority_code", db_index=True)
    property_company = models.ForeignKey(CompanyInfo, verbose_name=u"使用单位", null=True, blank=True,
                                         on_delete=models.SET_NULL, related_name="property_company_authority_code", db_index=True)
    maintain_company_name = models.CharField(max_length=256, verbose_name=u"维保单位名称", null=True, blank=True)
    property_company_name = models.CharField(max_length=256, verbose_name=u"使用单位名称", null=True, blank=True)
    ELEVATOR_1 = 10
    ELEVATOR_2 = 20
    ELEVATOR_3 = 30
    ELEVATOR_4 = 40
    ELEVATOR = (
        (10, u"曳引与强制驱动电梯"),
        (20, u"液压驱动电梯"),
        (30, u"杂物电梯"),
        (40, u"自动扶梯"),
    )
    elevator_type = models.IntegerField(choices=ELEVATOR, default=ELEVATOR_1, verbose_name=u"电梯类型", db_index=True)
    jump_layer = models.CharField(max_length=220, verbose_name=u"跳层", default="", null=True, blank=True)
    half_layer = models.CharField(max_length=220, verbose_name=u"半层", default="", null=True, blank=True)
    layer = models.CharField(max_length=220, verbose_name="楼层", default="", null=True, blank=True)
    surl = models.CharField(max_length=400, verbose_name=u"视频流地址", null=True, blank=True)

    def manufacturer(self):
        if self.manufacturer_code_elevator:
            manufacturer = Manufacturer.objects.filter_active(code=self.manufacturer_code_elevator).first()
            return manufacturer
        return None

    def manufacturer_name(self):
        # for item in ec:
        #     if item['manufacturer_code_elevator'] == self.manufacturer_code_elevator:
        #         return item['manufacturer_name']
        # return
        if self.manufacturer_code_elevator:
            manufacturer = Manufacturer.objects.filter_active(code=self.manufacturer_code_elevator).first()
            if manufacturer:
                return manufacturer.name
        return None

    def company_platform(self):
        return self.platform.name if self.platform else None

    def o(self):
        return self.device_code_elevator

    def f(self):
        return self.manufacturer_code_elevator

    def button_display(self):
        return "1" if self.manufacturer_code_elevator == u"1701001" else "0"

    def register_log(self):
        acrl = AuthorityCodeRegisterLog.objects.filter_active(authority_code=self).values("send", "rec")
        for a in acrl:
            try:
                send = json.loads(a['send'])
            except:
                send = a['send']
            try:
                rec = json.loads(a['rec'])
            except:
                rec = a['rec']

            a['send'] = send
            a['rec'] = rec
        return acrl

    @classmethod
    def belong_to_com(cls, device_code_elevator, company_id):
        ret = False
        company = CompanyInfo.objects.filter_active(id=company_id).first()
        if not company:
            return ret
        obj = cls.objects.filter_active(device_code_elevator=device_code_elevator).first()
        if obj and company.company_type == 100:
            ret = obj.maintain_company_id == company_id
        elif obj and company.company_type == 300:
            ret = obj.property_company_id == company_id
        return ret

    @classmethod
    def belong_to_organization(cls, device_code_elevator, org_id):
        from users.models import Organization, OrganizationElevatorRelation
        ret = False
        obj = cls.objects.filter_active(device_code_elevator=device_code_elevator).first()
        if obj:
            ret = OrganizationElevatorRelation.objects.filter_active(organization_id=org_id, register_code=obj.elevator_code).exists()
        return ret

    def internal_no(self):
        manufacturer = Manufacturer.objects.filter_active(code=self.manufacturer_code_elevator).first()
        if not manufacturer:
            return None
        ei = ElevatorInfo.objects.filter_active(factory_no=self.manufacturer_number_elevator, manufacturer_company=manufacturer).first()
        return ei.internal_no if ei else None


# 已废除
class AuthorityCodeUserRelation(BaseModel):
    """ 监控关注 """
    authority_code = models.ForeignKey(AuthorityCode, null=True, blank=True)
    user = models.ForeignKey(AuthUser, null=True, blank=True)


class AuthorityCodeRegisterLog(BaseModel):
    authority_code = models.ForeignKey(AuthorityCode, verbose_name=u"对应鉴权", null=True)
    send = models.TextField(default="", verbose_name=u"发送市局内容")
    rec = models.TextField(default="", verbose_name=u"收取内容")


class CompanyPlatform(BaseModel):
    name = models.CharField(verbose_name=u"企业平台", unique=True, max_length=100)
    web_name = models.CharField(verbose_name=u"平台应用名", max_length=100, blank=True, null=True)
    code = models.CharField(verbose_name=u"平台鉴权码", max_length=100, unique=True)
    CA0 = "0"
    CA1 = "1"
    CA = (
        (CA0, u"不可"),
        (CA1, u"可以"),
    )
    can_access = models.CharField(choices=CA, verbose_name=u"是否可以接入", default=CA0, db_index=True, max_length=1)
    domain = models.CharField(verbose_name=u"域名", blank=True, null=True, max_length=220)
    port = models.CharField(verbose_name=u"端口号", blank=True, null=True, max_length=10)
    unique_id = models.CharField(verbose_name=u"唯一识别id", db_index=True, unique=True, max_length=20)
    desc = models.CharField(verbose_name=u"描述", max_length=200, blank=True, null=True)

    def is_online(self):
        return 1

    def manufacturers(self):
        data = []
        cpmrs = CompanyPlatformManufacturerRelation.objects.filter_active(company_platform=self)
        for cpmr in cpmrs:
            if cpmr.manufacturer:
                data.append(cpmr.manufacturer.json_for_plat())
        return data


class Manufacturer(BaseModel):
    name = models.CharField(verbose_name=u"厂商名称", max_length=100, unique=True)
    brand_name = models.CharField(verbose_name=u"品牌名称", max_length=100, null=True, blank=True)
    code = models.CharField(max_length=20, verbose_name=u'厂家编号', null=True, unique=True)
    address = models.CharField(verbose_name=u"地址", max_length=100, null=True, blank=True)
    manu_phone = models.CharField(verbose_name=u"厂家电话", max_length=100, null=True, blank=True)
    contact = models.CharField(verbose_name=u"联系人", max_length=20, null=True, blank=True)
    contact_phone = models.CharField(verbose_name=u"联系人电话", max_length=20, null=True, blank=True)

    def json_for_plat(self):
        return {
            "id": self.id,
            "name": self.name,
            "code": self.code
        }


class CompanyPlatformManufacturerRelation(BaseModel):
    manufacturer = models.ForeignKey(Manufacturer, verbose_name=u"制造厂家", null=True, blank=True, db_index=True)
    company_platform = models.ForeignKey(CompanyPlatform, verbose_name=u"企业平台", null=True, blank=True, db_index=True)


# 电梯状态
class StatusMsg(BaseModel):
    """1 是 0 否 允许为null"""
    is_stopped = models.IntegerField(verbose_name=u'电梯停止', null=True)
    is_up = models.IntegerField(verbose_name=u'电梯上行', null=True)
    is_down = models.IntegerField(verbose_name=u'电梯下行', null=True)
    ele_status = models.IntegerField(verbose_name=u'轿门状态', null=True)  # 1 门关着的 0 开着的
    is_there_anyone = models.IntegerField(verbose_name=u'轿厢有人', null=True)
    is_overhauling = models.IntegerField(verbose_name=u'电梯检修', null=True)

    is_closed = models.IntegerField(verbose_name=u'轿厢门开关', null=True)  # 1关 0开  收到开关的信号(相对于状态 是个信号)
    base_station_is_closed = models.IntegerField(verbose_name=u'基站开关', null=True)  # TODO 待定 1关 0开
    upper_limit = models.IntegerField(verbose_name=u'上极限', null=True)  # 电梯冲顶的信号
    lower_limit = models.IntegerField(verbose_name=u'下极限', null=True)  # 电梯蹲地的信号
    upper_level = models.IntegerField(verbose_name=u'上平层', null=True)
    lower_level = models.IntegerField(verbose_name=u'下平层', null=True)
    body_induction = models.IntegerField(verbose_name=u'人体感应开关', null=True)  # TODO 待定 1 开 0 关 检测
    called = models.IntegerField(verbose_name=u'呼叫按钮', null=True)

    floor = models.IntegerField(verbose_name=u'楼层', null=True)
    authority_code = models.ForeignKey(AuthorityCode, verbose_name=u"对应鉴权", null=True, related_name="status_msg")

    def to_json(self):
        dic = {
            "is_stopped": self.is_stopped if self.is_stopped else 0,
            "is_up": self.is_up if self.is_up else 0,
            "is_down": self.is_down if self.is_down else 0,
            "ele_status": self.ele_status if self.ele_status else 0,
            "is_there_anyone": self.is_there_anyone if self.is_there_anyone else 0,
            "is_overhauling": self.is_overhauling if self.is_overhauling else 0,
            "is_closed": self.is_closed if self.is_closed else 0,
            "base_station_is_closed": self.base_station_is_closed if self.base_station_is_closed else 0,
            "upper_limit": self.upper_limit if self.upper_limit else 0,
            "lower_limit": self.lower_limit if self.lower_limit else 0,
            "upper_level": self.upper_level if self.upper_level else 0,
            "lower_level": self.lower_level if self.lower_level else 0,
            "body_induction": self.body_induction if self.body_induction else 0,
            "called": self.called if self.called else 0,
            "floor": self.floor,
            "authority_code": self.authority_code.code if self.authority_code else None,
            "update_time": str(self.update_time)
        }
        return dic

    def get_real_floor(self):
        if not self.authority_code.layer:
            real_floor = self.floor + self.authority_code.start_floor
            if self.authority_code.start_floor < 0 and real_floor >= 0:
                real_floor += 1
        else:
            layers = self.authority_code.layer.split(",")
            if len(layers) >= self.floor:
                real_floor = layers[self.floor - 1]
            else:
                layers = [int(float(i)) for i in layers]
                layers.sort()
                f = self.floor - len(layers)
                real_floor = f + max(layers)
        return str(real_floor)

    def get_elevator_status(self):
        if self.is_stopped:
            run_status = 0
        elif self.is_up:
            run_status = 1
        elif self.is_down:
            run_status = -1
        else:
            run_status = 0

        dic = {
            "run_status": run_status,  # 向上 向下 停止
            "floor": self.get_real_floor(),
            "is_open": 1 if not self.is_closed else 0
        }
        return dic


# 电梯报警
class AlarmMsg(BaseModel):
    """1 是 0 否 允许为null"""
    is_alarm = models.IntegerField(verbose_name=u'呼叫按钮', null=True)
    is_trapped = models.IntegerField(verbose_name=u'电梯困人', null=True)   # '2'
    stop_abnormal = models.IntegerField(verbose_name=u'非平层停梯', null=True)
    circuit_break = models.IntegerField(verbose_name=u'安全回路中断', null=True) # 1短接 0正常
    is_top = models.IntegerField(verbose_name=u'轿厢冲顶', null=True)
    is_bottom = models.IntegerField(verbose_name=u'轿厢蹲底', null=True)
    go_with_open = models.IntegerField(verbose_name=u'开门走梯', null=True)

    base_station_missed = models.IntegerField(verbose_name=u'基站丢失', null=True)
    accidental_movement = models.IntegerField(verbose_name=u'意外移动', null=True)
    flat_fault = models.IntegerField(verbose_name=u'平层故障', null=True)
    authority_code = models.ForeignKey(AuthorityCode, verbose_name=u"对应鉴权", null=True, related_name="alarm_msg")

    def to_json(self):
        dic = {
            "is_alarm": self.is_alarm if self.is_alarm else 0,
            "is_trapped": self.is_trapped if self.is_trapped else 0,
            "stop_abnormal": self.stop_abnormal if self.stop_abnormal else 0,
            "circuit_break": self.circuit_break if self.circuit_break else 0,
            "is_top": self.is_top if self.is_top else 0,
            "is_bottom": self.is_bottom if self.is_bottom else 0,
            "go_with_open": self.go_with_open if self.go_with_open else 0,
            "base_station_missed": self.base_station_missed if self.base_station_missed else 0,
            "accidental_movement": self.accidental_movement if self.accidental_movement else 0,
            "flat_fault": self.flat_fault if self.flat_fault else 0,
            "authority_code": self.authority_code.code if self.authority_code else None,
            "create_time": str(self.create_time)
        }
        return dic

    def get_elevator_alarm(self):
        alarm = []
        if self.is_alarm:
            alarm.append(DEV_RUN_STATE[1])
        if self.is_trapped:
            alarm.append(DEV_RUN_STATE[2])
        if self.stop_abnormal:
            alarm.append(DEV_RUN_STATE[3])
        if self.circuit_break:
            alarm.append(DEV_RUN_STATE[4])
        if self.is_top:
            alarm.append(DEV_RUN_STATE[5])
        if self.is_bottom:
            alarm.append(DEV_RUN_STATE[6])
        if self.go_with_open:
            alarm.append(DEV_RUN_STATE[7])
        return alarm

    def is_online(self):
        return 1 if self.authority_code.is_online else 0


class PlatformSession(BaseModel):
    ses = models.CharField(max_length=50, verbose_name=u"从平台获取的session", null=True)


class ElevatorMalfunction(BaseModel):
    """ 电梯故障工单 """
    MT1 = 0
    MT2 = 1
    MT = (
        (MT1, u"普通维修"),
        (MT2, u"物联网报修"),
    )
    maintenance_type = models.IntegerField(choices=MT, default=MT1, verbose_name=u"维修类型", db_index=True)
    register_code = models.CharField(max_length=32, verbose_name=u'电梯注册代码', null=True, db_index=True, db_column="Register_code")
    elevator = models.ForeignKey(ElevatorInfo, verbose_name=u"电梯", related_name="malfunction", db_index=True, null=True, blank=True)
    pro_no = models.CharField(max_length=40, verbose_name=u'出厂编号', null=True, db_column="ProNo", blank=True)
    factory_code = models.CharField(max_length=20, verbose_name=u'厂家编号', null=True, db_column='Factory_code')
    per_unique_code = models.CharField(max_length=56, verbose_name=u'外设唯一识别编号', db_column='Per_unique_code', null=True)
    alarm_time = models.DateTimeField(verbose_name=u"报警时间", db_column='Alarm_time', null=True)
    equ_loc_addr = models.CharField(max_length=200, verbose_name=u"使用地点", db_column="EqULocAddr", null=True)
    alarm_types = models.CharField(max_length=40, verbose_name=u"电梯报警类型", db_column="Alarm_types", null=True)
    notify_person = models.CharField(max_length=30, verbose_name=u"通知人员", db_column="Notify_person", null=True)
    S0 = 0
    S01 = 1
    S1 = 10
    S2 = 20
    S3 = 30
    S4 = 40
    S5 = 50
    S6 = 60
    S7 = 70
    Status = (
        (S0, u"报修"),   # app创建后的状态
        (S01, u"报警待指派"),   # app创建后的状态
        (S1, u"已创建"),
        (S2, u"已确认"),
        (S3, u"已退回"),
        (S4, u"到达现场"),
        (S5, u"维修完成"),
        (S6, u"问题消除"),
        (S7, u"物业确认"),
    )
    status = models.IntegerField(choices=Status, default=S1, verbose_name=u"工单状态", db_column="Status")
    eliminate_time = models.DateTimeField(verbose_name=u"消警时间", db_column="Eliminate_time", null=True)
    start_planning_time = models.DateField(verbose_name=u"计划开始维修时间", null=True)
    end_planning_time = models.DateField(verbose_name="计划完成维修时间", null=True)
    maintain_company = models.ForeignKey(CompanyInfo, verbose_name=u"维保单位", null=True,
                                         related_name="maintain_malfunction")
    property_company = models.ForeignKey(CompanyInfo, verbose_name=u"使用单位", null=True,
                                         related_name="property_malfunction")
    property_company_name = models.CharField(max_length=200, verbose_name="使用单位名称", null=True, blank=True)
    maintain_company_name = models.CharField(max_length=200, verbose_name="维保单位名称", null=True, blank=True)
    IT0 = 0
    IT1 = 1
    IT = (
        (IT1, u"是"),
        (IT0, u"否"),
    )
    is_trapped = models.IntegerField(choices=IT, verbose_name=u"是否关人", default=IT0)
    is_emergency = models.IntegerField(choices=IT, verbose_name=u"是否紧急", default=IT0)
    desc = models.CharField(max_length=1024, verbose_name=u"故障描述", default="", null=True, blank=True)
    solution = models.CharField(max_length=1024, verbose_name=u"处理情况", default="", null=True, blank=True)
    reason = models.CharField(max_length=1024, verbose_name=u"故障原因", default="", null=True, blank=True)
    work_hours = models.DecimalField(max_digits=8, decimal_places=2, verbose_name=u"工时", default=0, null=True, blank=True)
    work_hours_success = models.DecimalField(max_digits=8, decimal_places=2, verbose_name=u"实际工时", default=0, null=True, blank=True)
    costs = models.DecimalField(max_digits=16, decimal_places=2, verbose_name=u"预估费用", default=0, null=True, blank=True)
    create_user = models.ForeignKey(AuthUser, verbose_name=u"创建人员", null=True, blank=True)
    pic = models.CharField(max_length=1024, verbose_name=u"照片", null=True, blank=True)
    pic_success = models.CharField(max_length=1024, verbose_name=u"照片", null=True, blank=True)
    signature = models.CharField(max_length=128, verbose_name=u"签名", null=True, blank=True)
    time_points = models.CharField(max_length=1024, verbose_name=u"各个时间点", null=True, blank=True)
    actual_costs = models.DecimalField(max_digits=16, decimal_places=2, verbose_name=u"实际费用", default=0, null=True)
    fault = models.ForeignKey('ElevatorFault', null=True, blank=True, verbose_name=u"故障单id")

    class Meta:
        db_table = "elevator_malfunction"

    def qr_code(self):
        return self.elevator.qr_code if self.elevator else None

    def pictures(self):
        return self.pic.split(",") if self.pic else []

    def pictures_success(self):
        return self.pic_success.split(",") if self.pic_success else []

    def repair_content(self):
        rcemrs = RepairContentElevatorMalfunctionRelation.objects.filter_active(elevator_malfunction_id=self.id)
        if not rcemrs:
            return []
        l = []
        for obj in rcemrs:
            l.append({
                "id": obj.repair_content.id,
                "content": obj.repair_content.content,
                "repair_type": obj.repair_content.id,
                "repair_type_name": obj.repair_content.name(),
                "number": obj.number,
                "costs": obj.repair_content.costs(),
                "name": obj.repair_content.name()
            })
        return l

    def notify_person_ids(self):
        emprs = ElevatorMalfunctionPersonRelation.objects.filter_active(elevator_malfunction=self).values_list("person_id", flat=True).distinct()
        return emprs

    def time_points_dic(self):
        if self.time_points:
            l = json.loads(self.time_points)
            tp0 = l.pop("0", None)
            tp10 = l.pop("10", None)
            if tp0:
                l.update({"0": tp0})
            elif tp10:
                l.update({"0": tp10})
            return l
        else:
            return {}

    def create_by_user(self):
        return self.create_user.username if self.create_user else ""

    def signature_success(self):
        emfd = ElevatorMalfunctionDeal.objects.filter_active(elevator_malfunction=self).last()
        return emfd.signature if emfd else ""


class ElevatorMalfunctionDeal(BaseModel):
    """ 故障单记录表 """
    elevator_malfunction = models.ForeignKey(ElevatorMalfunction, verbose_name=u"电梯故障工单", db_index=True)
    register_code = models.CharField(max_length=32, verbose_name=u'电梯注册代码', null=True, db_index=True, db_column="Register_code")
    elevator = models.ForeignKey(ElevatorInfo, verbose_name=u"电梯", related_name="malfunction_detail", db_index=True)
    recv_person = models.CharField(max_length=200, verbose_name=u"当前处理人员", null=True, db_column="Recv_Person")
    send_person = models.CharField(max_length=200, verbose_name=u"指派人员", null=True, db_column="Send_person")
    jecv_time = models.DateTimeField(verbose_name=u"接到处理时间", null=True, db_column="Recv_time")
    alarm_time = models.DateTimeField(verbose_name=u"报警时间", null=True, db_column="Alarm_time")
    costs = models.DecimalField(max_digits=16, decimal_places=2, verbose_name=u"实际费用", default=0, null=True)
    desc = models.CharField(max_length=1024, verbose_name=u"故障描述", default="", null=True, blank=True)
    solution = models.CharField(max_length=1024, verbose_name=u"处理情况", default="", null=True, blank=True)
    work_hours = models.DecimalField(max_digits=8, decimal_places=2, verbose_name=u"工时", default=0, null=True, blank=True)
    signature = models.CharField(max_length=128, verbose_name=u"签名", null=True, blank=True)
    pic_success = models.CharField(max_length=1024, verbose_name=u"照片", null=True, blank=True)
    S0 = 0
    S1 = 10
    S2 = 20
    S3 = 30
    S4 = 40
    S5 = 50
    S6 = 60
    S7 = 70
    Status = (
        (S0, u"报修"),   # app创建后的状态
        (S1, u"已创建"),
        (S2, u"已确认"),
        (S3, u"已退回"),
        (S4, u"到达现场"),
        (S5, u"问题解决"),
        (S6, u"问题消除"),
        (S7, u"物业确认"),
    )
    status = models.IntegerField(choices=Status, default=S1, verbose_name=u"工单状态", null=True, db_column="Status")

    class Meta:
        db_table = "elevator_malfunction_deal"


class ElevatorMalfunctionPersonRelation(BaseModel):
    """ 故障和指派人员关联关系表 """
    elevator_malfunction = models.ForeignKey(ElevatorMalfunction, verbose_name=u"故障工单", null=True, db_index=True)
    person = models.ForeignKey(Person, verbose_name=u"维修人员", null=True)

    def get_username(self):
        return self.person.auth_user.real_name


class RepairType(BaseModel):
    """ 维修类型 """
    name = models.CharField(max_length=1024, verbose_name="维修类型")

    # def can_be_modified(self):
    #     return self.service_id != 0


class RepairContent(BaseModel):
    """ 维修项目 """
    content = models.CharField(max_length=1024, verbose_name=u"维修内容", default="", null=True, blank=True)
    repair_type = models.ForeignKey(RepairType, verbose_name=u"维修类型", db_index=True)
    comment = models.CharField(max_length=300, verbose_name=u"备注", default="", null=True, blank=True)

    def repair_type_name(self):
        return self.repair_type.name if self.repair_type else None

    # def can_be_modified(self):
    #     return self.service_id != 0

    def name(self):
        cc = self.content_costs.all().filter(service_id=self.service_id).first()
        return cc.name if cc else None

    def costs(self):
        cc = self.content_costs.all().filter(service_id=self.service_id).first()
        return cc.costs if cc else None

    def to_json(self):
        return {
            "id": self.id,
            "content": self.content,
            "repair_type": self.repair_type.id,
            "costs": self.costs(),
            "comment": self.comment,
            "repair_type_name": self.repair_type_name(),
            "can_be_modified": False,
            "name": self.name()
        }


class ContentCosts(BaseModel):
    """ 单个项目 名称 费用 """
    costs = models.DecimalField(max_digits=16, decimal_places=2, verbose_name=u"单个费用", default=0, null=True)
    name = models.CharField(max_length=50, verbose_name=u"维修项目名称", null=True, blank=True)
    repair_content = models.ForeignKey(RepairContent, verbose_name=u"维修项目", related_name="content_costs", db_index=True)


class RepairContentElevatorMalfunctionRelation(BaseModel):
    """ 维修和维修项目的关联关系 """
    elevator_malfunction = models.ForeignKey(ElevatorMalfunction, related_name="content_relation", verbose_name="维修工单", db_index=True)
    repair_content = models.ForeignKey(RepairContent, related_name="content_relation", verbose_name="项目", db_index=True)
    number = models.IntegerField(default=1, verbose_name=u"数量")  # 当使用多个重复的配件时 改变number值即可


# 鉴权信息
class User(BaseModel):
    # ip = models.CharField(max_length=20, default=u'', verbose_name=u'ip地址', null=True)
    session = models.CharField(max_length=50, default=u'', verbose_name=u'session', null=True)
    manufacturer_id = models.CharField(max_length=20, default=u'', verbose_name=u'厂家ID', null=True)
    authority_code = models.CharField(max_length=20, default=u'', verbose_name=u'鉴权码', null=True)
    expire_time = models.IntegerField(default=0, verbose_name=u'过期时间戳', null=True)


# 电梯注册
class ElevatorRegister(BaseModel):
    f = models.CharField(default=u'', max_length=20, verbose_name=u'厂家编号', null=True)
    mn = models.CharField(default=u'', max_length=20, verbose_name=u'电梯出厂编号', null=True)
    o = models.CharField(default=u'', max_length=50, verbose_name=u'外设编号', null=True)
    e = models.CharField(default=u'', max_length=25, verbose_name=u'电梯注册代码', null=True)
    T1 = "01"
    T2 = "02"
    T3 = "03"
    T = (
        (T1, u"采集器"),
        (T2, u"摄像头"),
        (T3, u"高清屏"),
    )
    t = models.CharField(choices=T, max_length=10, verbose_name=u'外设类型', null=True)
    S0 = "0"
    S1 = "1"
    S = (
        (S0, u"不在线"),
        (S1, u"在线"),
    )
    s = models.CharField(choices=S, max_length=5, verbose_name=u'是否在线', null=True)
    tm = models.CharField(default=u'', max_length=20, verbose_name=u'外设发送时间戳', null=True)


# 电梯在线数
class ElevatorONLIne(BaseModel):
    f = models.CharField(default=u'', max_length=20, verbose_name=u'厂家编号', null=True)
    tn = models.CharField(default=u'', verbose_name=u'接入平台总数量', null=True, max_length=128)
    on = models.CharField(default=u'', verbose_name=u'电梯在线数量', null=True, max_length=128)
    t = models.CharField(default=u'', verbose_name=u'发送时间戳', null=True, max_length=128)


# 外设在线状态
class ElevatorCollector(BaseModel):
    f = models.CharField(default=u'', max_length=50, verbose_name=u'厂家编号', null=True)
    e = models.CharField(default=u'', max_length=25, verbose_name=u'电梯注册代码', null=True)
    o = models.CharField(default=u'', max_length=50, verbose_name=u'外设编号', null=True)
    t = models.CharField(default=u'', max_length=50, verbose_name=u'外设类型', null=True)
    s = models.BooleanField(default=True, verbose_name=u'是否在线')
    t1 = models.CharField(default=u'', max_length=20, verbose_name=u'外设发送时间戳', null=True)
    t2 = models.CharField(default=u'', max_length=20, verbose_name=u'平台发送时间戳', null=True)


# 外设在线率
class ElevatorCollectorOnlineRate(BaseModel):
    f = models.CharField(default=u'', max_length=50, verbose_name=u'厂家编号', null=True)
    t = models.CharField(default=u'', max_length=50, verbose_name=u'外设类型', null=True)
    r = models.CharField(default=u'', max_length=10, verbose_name=u'外设在线率', null=True)
    tm = models.CharField(default=u'', max_length=20, verbose_name=u'平台发送时间戳', null=True)


# 电梯状态
class ElevatorStatus(BaseModel):
    f = models.CharField(default=u'', max_length=50, verbose_name=u'厂家编号', null=True)
    e = models.CharField(default=u'', max_length=25, verbose_name=u'电梯注册代码', null=True)
    o = models.CharField(default=u'', max_length=50, verbose_name=u'外设编号', null=True)
    U = (
        ('0', u'未上行'),
        ('1', u'上行')
    )
    u = models.CharField(choices=U, null=True, verbose_name=u'上行信号', max_length=5)
    D = (
        ('0', u'未下行'),
        ('1', u'下行')
    )
    d = models.CharField(choices=D, null=True, verbose_name=u'下行信号', max_length=5)
    LM = (
        # ('m', u'检修'),
        # ('a', u'正常运行'),
        # ('d', u'司机'),
        # ('f', u'消防'),
        # ('l', u'锁梯'),
        # ('e', u'应急电源运行'),
        ('0', u'停止服务'),
        ('1', u'正常运行'),
        ('2', u'检修'),
        ('3', u'消防返回'),
        ('4', u'消防员运行'),
        ('5', u'应急电源运行'),
        ('6', u'地震模'),
        ('7', u'未知'),
    )
    lm = models.CharField(choices=LM, null=True, verbose_name=u'电梯模式', max_length=5)
    RS = (
        ('0', u'未运行'),
        ('1', u'运行')
    )
    rs = models.CharField(choices=RS, null=True, verbose_name=u'运行信号', max_length=5)
    OD = (
        ('0', u'无信号'),
        ('1', u'有信号')
    )
    od = models.CharField(choices=OD, null=True, verbose_name=u'开门信号', max_length=5)
    OM = (
        ('0', u'未到位'),
        ('1', u'已到位')
    )
    om = models.CharField(choices=OM, null=True, verbose_name=u'开门到位', max_length=5)
    SD = (
        ('0', u'无信号'),
        ('1', u'有信号')
    )
    sd = models.CharField(choices=SD, null=True, verbose_name=u'关门信号', max_length=5)
    SM = (
        ('0', u'未到位'),
        ('1', u'已到位')
    )
    sm = models.CharField(choices=SM, null=True, verbose_name=u'关门到位', max_length=5)
    OB = (
        ('0', u'无信号'),
        ('1', u'有信号')
    )
    ob = models.CharField(choices=OB, null=True, verbose_name=u'开门按钮信号', max_length=5)
    DZ = (
        ('0', u'无信号'),
        ('1', u'有信号')
    )
    dz = models.CharField(choices=DZ, null=True, verbose_name=u'门区信号', max_length=5)
    OL = (
        ('0', u'未超载'),
        ('1', u'超载')
    )
    ol = models.CharField(choices=OL, null=True, verbose_name=u'超载信号', max_length=5)
    FL = (
        ('0', u'未满载'),
        ('1', u'满载')
    )
    fl = models.CharField(choices=FL, null=True, verbose_name=u'满载信号', max_length=5)
    PS = (
        ('0', u'无人'),
        ('1', u'有人')
    )
    ps = models.CharField(choices=PS, null=True, verbose_name=u'电梯内是否有人', max_length=5)
    cp = models.CharField(max_length=3, default=u'', verbose_name=u'电梯所在楼层', null=True)
    rc = models.CharField(max_length=30, default=u'', verbose_name=u'运行次数', null=True)
    dc = models.CharField(max_length=30, default=u'', verbose_name=u'开关门次数', null=True)
    rt = models.CharField(max_length=30, default=u'', verbose_name=u'运行时间', null=True)
    t = models.CharField(max_length=14, default=u'', verbose_name=u'设备状态变化时间', null=True)

    # manufacturer_number_elevator = models.CharField(default=u'', max_length=50, verbose_name=u'电梯出厂编号', null=True)
    # address = models.CharField(default=u"", max_length=100, verbose_name=u"电梯使用位置", null=True, blank=True)
    # maintain_company_name = models.CharField(max_length=100, verbose_name=u"维保单位名称", null=True, blank=True)
    # property_company_name = models.CharField(max_length=100, verbose_name=u"使用单位名称", null=True, blank=True)
    # product_company_name = models.CharField(max_length=100, verbose_name=u"制造单位名称", null=True, blank=True)
    # company_platform = models.CharField(max_length=100, verbose_name=u"企业平台", null=True, blank=True)
    # internal_no = models.CharField(max_length=50, verbose_name=u"内部编号", null=True, blank=True)

    def is_online(self):
        b = 0
        ac = self.get_authority_code()
        if ac and ac.is_online:
            b = 1
        # return 1 if self.update_time + datetime.timedelta(minutes=5) > datetime.datetime.now() else 0
        return b

    def is_open(self):
        return 1 if self.om == "1" else 0

    def run_status(self):
        if self.u == "1":
            return 1
        elif self.d == "1":
            return -1
        else:
            return 0

    def get_authority_code(self):
        if self.o:
            ac = AuthorityCode.objects.filter_active(device_code_elevator=self.o).first()
            if ac:
                return ac
        return None

    def manufacturer_number_elevator(self):
        ac = self.get_authority_code()
        if ac:
            return ac.manufacturer_number_elevator
        return None

    def address(self):
        ac = self.get_authority_code()
        if ac:
            return ac.address
        return None

    def maintain_company_name(self):
        ac = self.get_authority_code()
        if ac:
            return ac.maintain_company_name
        return None

    def property_company_name(self):
        ac = self.get_authority_code()
        if ac:
            return ac.property_company_name
        return None

    def product_company_name(self):
        ac = self.get_authority_code()
        if ac and ac.manufacturer_code_elevator:
            manu = Manufacturer.objects.filter_active(code=ac.manufacturer_code_elevator).first()
            if manu:
                return manu.name
        return None

    def company_platform(self):
        ac = self.get_authority_code()
        if ac and ac.platform:
            return ac.platform.name
        return None

    def internal_no(self):
        ac = self.get_authority_code()
        if ac:
            return ac.address
        return None

    def button_display(self):
        return "1" if self.f == u"1701001" else "0"

    def inner_no(self):
        if self.o:
            ac = AuthorityCode.objects.filter_active(manufacturer_code_elevator=self.o).first()
            if ac and ac.elevator_code:
                elevator = ElevatorInfo.objects.filter_active(register_code=ac.elevator_code).first()
                return elevator.internal_no
        return None


# 电梯故障
class ElevatorFault(BaseModel):
    f = models.CharField(default=u'', max_length=50, verbose_name=u'厂家编号', null=True)
    e = models.CharField(default=u'', max_length=25, verbose_name=u'电梯注册代码', null=True)
    o = models.CharField(default=u'', max_length=50, verbose_name=u'外设编号', null=True)
    S = (
        ('e', u'产生'),
        ('c', u'消除')
    )
    s = models.CharField(null=True, choices=S, verbose_name=u'报警状态', max_length=5)
    # 0=无故障，1=轿厢报警按钮，2=电梯困人，3=非平层停梯，4=安全回路断路，5=轿厢冲顶，6=轿厢蹲底， 7=开门走梯， 8=电梯速度异常,
    # 9=电梯运行时安全回路断路10=关门故障, 11=开门故障, 12=轿厢在开锁区域外停止，13=轿厢意外移动,14=电动机运转时间限制器动作,
    # 15=楼层位置丢失,16=其他阻止电梯再启动的故障。多个时用以半角逗号分隔的字符串，如“1,2,3”
    a = models.CharField(default=u'', verbose_name=u'故障代码', max_length=128, null=True)
    er = models.CharField(default=u'', verbose_name=u'其他故障代码', max_length=5, null=True)
    t = models.CharField(max_length=14, default=u'', verbose_name=u'设备报警时间', null=True)
    alarm_id = models.IntegerField(verbose_name=u"故障id", null=True, blank=True)  # 朱的数据对应id
    sn = models.CharField(max_length=30, default=u'', verbose_name=u'编号', null=True)
    notify_person = models.ForeignKey(Person, null=True, blank=True, verbose_name=u"通知人员")
    receipt_status = models.CharField(max_length=200, null=True, blank=True, verbose_name=u"回执状态")
    notify_method = models.CharField(max_length=200, null=True, blank=True, verbose_name=u"通知方式")

    def get_authority_code(self):
        if self.o:
            ac = AuthorityCode.objects.filter_active(device_code_elevator=self.o).first()
            if ac:
                return ac
        return None

    def property_company(self):
        ac = self.get_authority_code()
        if ac:
            return ac.property_company_name
        return None

    def inner_no(self):
        if self.o:
            ac = AuthorityCode.objects.filter_active(manufacturer_code_elevator=self.o).first()
            if ac and ac.elevator_code:
                elevator = ElevatorInfo.objects.filter_active(register_code=ac.elevator_code).first()
                return elevator.internal_no
        return None

    def address(self):
        ac = self.get_authority_code()
        if ac:
            return ac.address if ac.address else u""
        return u""

    def content(self):
        ret = ""
        dic = {
            "1": u"轿厢报警按钮", "2": u"电梯困人", "3": u"非平层停梯", "4": u"安全回路断路",
            "5": u"轿厢冲顶", "6": u"轿厢蹲底", "7": u"开门走梯", "8": u"电梯速度异常", "9": u"电梯运行时安全回路断路",
            "10": u"关门故障", "11": u"开门故障", "12": u"轿厢在开锁区域外停止", "13": u"轿厢意外移动",
            "14": u"电动机运转时间限制器动作", "15": u"楼层位置丢失", "16": u"其他阻止电梯再启动的故障"
        }
        # dic = {"0": u"无故障", "1": u"轿厢报警按钮", "2": u"电梯困人", "3": u"非平层停梯", "4": u"安全回路断路", "5": u"轿厢冲顶", "6":u"轿厢蹲底", "7": u"开门走梯"}
        if self.a:
            l = self.a.split(",")
            for i in l:
                ret += dic.get(i, "")
        return ret

    def alarm_position(self):
        if self.o:
            ac = AuthorityCode.objects.filter_active(device_code_elevator=self.o).first()
            if ac:
                elevator_code = ac.elevator_code
                if elevator_code:
                    ei = ElevatorInfo.objects.filter_active(register_code=elevator_code).first()
                    if ei:
                        return ei.address
        return None

    def manufacturer_number(self):
        if self.o:
            ac = AuthorityCode.objects.filter_active(device_code_elevator=self.o).first()
            if ac:
                return ac.manufacturer_number_elevator
            return None

    def register_code(self):
        if self.o:
            ac = AuthorityCode.objects.filter_active(device_code_elevator=self.o).first()
            if ac:
                return ac.elevator_code
            return None

    def elevator(self):
        if self.o:
            ac = AuthorityCode.objects.filter_active(device_code_elevator=self.o).first()
            if ac:
                elevator_code = ac.elevator_code
                if elevator_code:
                    ei = ElevatorInfo.objects.filter_active(register_code=elevator_code).first()
                    if ei:
                        return ei.id
        return 0

    def is_online(self):
        if self.o:
            ac = AuthorityCode.objects.filter_active(device_code_elevator=self.o).first()
            if ac:
                return 1 if ac.is_online else 0
        return 0

    def alarm_type(self):
        try:
            alarms = self.a.split(",")
            alarm = []
            for i in alarms:
                if i == "1":
                    alarm.append(DEV_RUN_STATE[0])
                elif i == "2":
                    alarm.append(DEV_RUN_STATE[1])
                elif i == "3":
                    alarm.append(DEV_RUN_STATE[2])
                elif i == "4":
                    alarm.append(DEV_RUN_STATE[3])
                elif i == "5":
                    alarm.append(DEV_RUN_STATE[4])
                elif i == "6":
                    alarm.append(DEV_RUN_STATE[5])
                elif i == "7":
                    alarm.append(DEV_RUN_STATE[6])
                if i == "8":
                    alarm.append(DEV_RUN_STATE[7])
                elif i == "9":
                    alarm.append(DEV_RUN_STATE[8])
                elif i == "10":
                    alarm.append(DEV_RUN_STATE[9])
                elif i == "11":
                    alarm.append(DEV_RUN_STATE[10])
                elif i == "12":
                    alarm.append(DEV_RUN_STATE[11])
                elif i == "13":
                    alarm.append(DEV_RUN_STATE[12])
                elif i == "14":
                    alarm.append(DEV_RUN_STATE[13])
                elif i == "15":
                    alarm.append(DEV_RUN_STATE[14])
                elif i == "16":
                    alarm.append(DEV_RUN_STATE[15])
            return alarm
        except:
            return []

    def status_id(self):
        ac = self.get_authority_code()
        return ac.id if ac else None


# 电梯故障处理
class ElevatorFaultDeal(BaseModel):
    e = models.CharField(default=u'', max_length=25, verbose_name=u'电梯注册代码', null=True)
    a = models.CharField(default=u'', verbose_name=u'故障代码', max_length=128, null=True)
    er = models.CharField(default=u'', verbose_name=u'其他故障代码', max_length=5, null=True)
    fid = models.IntegerField(verbose_name=u"故障id", null=True)
    sp = models.CharField(max_length=128, verbose_name=u'派单人员', null=True)
    st = models.CharField(max_length=14, default=u'', verbose_name=u'派单时间', null=True)
    rp = models.CharField(max_length=128, verbose_name=u'派工人员', null=True)
    t = models.CharField(max_length=14, default=u'', verbose_name=u'设备报警时间', null=True)


# 电梯事件
class ElevatorEvent(BaseModel):
    f = models.CharField(default=u'', max_length=50, verbose_name=u'厂家编号', null=True)
    e = models.CharField(default=u'', max_length=25, verbose_name=u'电梯注册代码', null=True)
    o = models.CharField(default=u'', max_length=50, verbose_name=u'外设编号', null=True)
    AM = (
        ('0', u'未恢复'),
        ('1', u'恢复')
    )
    am = models.CharField(choices=AM, default='0', verbose_name=u'电梯是否恢复自动运行模式', max_length=5)
    P = (
        ('0', u'未断电'),
        ('1', u'断电')
    )
    p = models.CharField(choices=P, default='0', verbose_name=u'主电源是否断电', max_length=5)
    SS = (
        ('0', u'未停止'),
        ('1', u'停止')
    )
    ss = models.CharField(choices=SS, default='0', verbose_name=u'停止服务', max_length=5)
    OM = (
        ('0', u'未进入检修'),
        ('1', u'进入检修')
    )
    om = models.CharField(choices=OM, default='0', verbose_name=u'检修模式', max_length=5)
    RM = (
        ('0', u'未进入消防返回模式'),
        ('1', u'进入消防返回模式')
    )
    rm = models.CharField(choices=RM, default='0', verbose_name=u'是否进入消防返回模式', max_length=5)
    FM = (
        ('0', u'未进入消防员运行模式'),
        ('1', u'进入消防员运行模式')
    )
    fm = models.CharField(choices=FM, default='0', verbose_name=u'是否进入消防员运行模式', max_length=5)
    EPM = (
        ('0', u'未进入应急电源运行'),
        ('1', u'进入应急电源运行')
    )
    epm = models.CharField(choices=EPM, default='0', verbose_name=u'应急电源运行', max_length=5)
    EM = (
        ('0', u'未进入地震运行模式'),
        ('1', u'进入地震运行模式')
    )
    em = models.CharField(choices=EM, default='0', verbose_name=u'地震运行模式', max_length=5)
    oc = models.CharField(default=u'', verbose_name=u'其他事件代码', max_length=5)
    t = models.CharField(max_length=14, default=u'', verbose_name=u'事件发生时间', null=True)


# 电梯统计
class ElevatorStatistics(BaseModel):
    f = models.CharField(default=u'', max_length=50, verbose_name=u'厂家编号', null=True)
    e = models.CharField(default=u'', max_length=25, verbose_name=u'电梯注册代码', null=True)
    bc = models.CharField(default=u'', max_length=128, verbose_name=u'钢丝绳折弯次数')
    rc = models.CharField(default=u'', max_length=128, verbose_name=u'运行次数')
    dc = models.CharField(default=u'', max_length=128, verbose_name=u'开关门次数')
    rt = models.CharField(default=u'', max_length=128, verbose_name=u'运行时间')
    t = models.CharField(max_length=14, default=u'', verbose_name=u'事件发生时间', null=True)


# 电梯报警
class ElevatorWarning(BaseModel):
    f = models.CharField(default=u'', max_length=50, verbose_name=u'厂家编号', null=True)
    o = models.CharField(default=u'', max_length=50, verbose_name=u'外设编号', null=True)
    S = (
        ('e', u'产生'),
        ('c', u'消除')
    )
    s = models.CharField(choices=S, default='c', verbose_name=u'报警状态', max_length=5)
    a = models.CharField(default=u'', max_length=20, verbose_name=u'电梯报警')
    t = models.CharField(max_length=14, default=u'', verbose_name=u'设备报警时间', null=True)


class ElevatorFaultAnalysis(BaseModel):
    """ 故障会诊及分析 """
    name = models.CharField(verbose_name=u"故障名称", max_length=50, default="", null=True, blank=True)
    etype = models.CharField(verbose_name=u"故障类型", max_length=50, default="", null=True, blank=True)
    solution = models.CharField(verbose_name=u"解决办法", max_length=1024, default="", null=True, blank=True)
    property_company = models.ForeignKey(CompanyInfo, verbose_name=u"使用单位", null=True, blank=True, db_index=True)
    property_company_name = models.CharField(verbose_name=u"使用单位名称", default="", max_length=200, null=True)
    auth_user = models.ForeignKey(AuthUser, verbose_name=u"解决人", null=True, blank=True, db_index=True)
    username = models.CharField(verbose_name=u"解决人", default="", max_length=20, null=True)
    stime = models.DateField(verbose_name=u"解决时间", null=True, blank=True, db_index=True)

    def materials(self):
        mffs = MaterialForFault.objects.filter_active(fault_analysis=self).values("name", "pictures")
        return mffs


class MaterialForFault(BaseModel):
    """ 素材 """
    fault_analysis = models.ForeignKey(ElevatorFaultAnalysis, verbose_name=u"故障", db_index=True, blank=True, null=True)
    name = models.CharField(verbose_name=u"故障名称", max_length=50, default="", null=True, blank=True)
    pictures = models.CharField(verbose_name=u"图片地址", max_length=1024, default="", null=True, blank=True)





































